package com.itheima.common;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class FileController {

    @PostMapping("/upload")
    @ResponseBody
    public R<Object> uploadFile(@RequestBody MultipartFile file, HttpServletRequest req) {
        try {

            SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
            String format = sd.format(new Date());

            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀名
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());

            //新生成文件名
            String fileName = UUID.randomUUID().toString() + System.currentTimeMillis() + fileSuffix;

            //上传文件到URL
            file.transferTo(new File("D:/phpstudy_pro/WWW/image/" + fileName));

            String path = "/image/" + fileName;

            //生成全路径名
//            String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/common/upload/" + format + fileName;

            return new R<>(1, "上传成功", path, null);

        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }


    @GetMapping("/download")
    @ResponseBody
    public void downloadFile(String name, HttpServletResponse response) throws IOException {

        String filename = name.split("/")[1];
        File newfile = new File("D:/upload" + File.separator+filename);
        if (!newfile.exists()) {
            throw new IOException(name + "文件不存在");
        }
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);

        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(newfile);
            bis = new BufferedInputStream(fis);
            os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            os.close();
            bis.close();
            fis.close();
        }
    }
}
